package org.example.ftp.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.Map;
import java.util.Properties;

/**
 * Mybatis插件围绕的四大接口：
 * Executor(update,query,flushStatements,commit,rollback,getTransaction,close,isClosed)拦截执行器的方法
 * ParameterHandler(getParameterObject,setParameters)拦截参数的处理
 * ResultSetHandler(handleResultSets,handleOutputParameters)拦截结果集的处理
 * StatementHandler(prapare,parameterize,batch,update,query)拦截sql语法构建的处理
 */
@Slf4j
//@Component
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class MybatisPageInterceptor implements Interceptor {
    private Properties properties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println(invocation);
        //通过StatementHandler获取执行的sql
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        Map<String,Object> parameterObject = (Map<String, Object>) statementHandler.getParameterHandler().getParameterObject();
        System.out.println(parameterObject);
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();
        Object sqlParameterObject = boundSql.getParameterObject();

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }
}
